import {TreePage} from 'weaver-mobile-page';
import React from 'react';
import {Tools} from "weaver-mobile";

const getLabel = Tools.getLabel;
const params = {
    org: {
        url: "/api/hrm/base/getHrmSearchTree",
        params: {isLoadUser: 1}
    },
    sub: {
        url: "/api/hrm/base/getHrmResourceTree"
    }
}

/**
 * 获取组织下属树
 * eg:查看下属和查看组织
 * jiansong 2019/11/8
 */
class WrOrg extends React.Component {

    componentDidMount() {
        const {type, orgStore} = this.props
        if (type == "sub") {
            orgStore.rootKey = "rootManager"
        } else {
            orgStore.rootKey = "rootCompany"
        }
        orgStore.getData(params[type], 2);
    }

    //当type更新时，刷新数据
    componentWillReceiveProps(nextProps) {
        const {orgStore} = this.props
        if (nextProps.type == "sub") {
            orgStore.rootKey = "rootManager"
        } else {
            orgStore.rootKey = "rootCompany"
        }
        orgStore.getData(params[nextProps.type], 2);
    }

    render() {
        const {type, onSelect, orgStore} = this.props;
        return (
            <div className="roll">
                <TreePage.Normal
                    async
                    store={orgStore}
                    params={params[type]}
                    decorator={content => (
                        <div onClick={event => this.handleSelect(content, event, onSelect)}>{content}</div>
                    )}
                />
            </div>
        );
    }

    handleSelect = (content, event, onSelect) => {
        if (!(event.target.tagName == "use" || event.target.tagName == "svg" || event.target.className == "am-tree-extend")) {
            let value = content.key || content._owner.key
            const {orgStore: {datas}} = this.props
            let val = this.getData([datas], value)
            if (val && val.type != 0) {
                onSelect(val.id, [{id: val.id, name: val.name}], val.type);
            }
        }
    }

    //循环获取数据
    getData = (datas, key) => {
        let val;
        datas.some(item => {
            if (item.key == key) {
                val = item;
                return true
            }
            if (item.childs) {
                val = this.getData(item.childs, key)
                if (val) {
                    return true;
                }
            }
        })
        return val
    }
}

export default WrOrg;
